<template>
  <div class="item-management">
    <div class="header">
      <h2>项目管理</h2>
      <el-button type="primary" @click="openItemForm">
        <el-icon><Plus /></el-icon>
        新建项目
      </el-button>
    </div>

    <!-- 项目列表 -->
    <el-table 
      :data="items" 
      style="width: 100%" 
      v-loading="loading.items"
      empty-text="暂无项目数据"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="图标" width="80" align="center">
        <template #default="scope">
          <div class="icon-display">
            <img 
              v-if="scope.row.icon" 
              :src="scope.row.icon" 
              :alt="scope.row.name"
              class="item-icon"
            />
            <el-icon v-else class="default-icon">
              <Document />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="120" show-overflow-tooltip />
      <el-table-column prop="content_type" label="类型" width="100">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.content_type)">
            {{ getTypeLabel(scope.row.content_type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="api_endpoint" label="API端点" width="100" show-overflow-tooltip />
      <el-table-column prop="description" label="描述" width="150" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <div class="action-buttons">
            <el-button size="small" @click="editItem(scope.row)">
              编辑
            </el-button>
            <el-button size="small" @click="viewContent(scope.row)">
              查看
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteItem(scope.row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 项目表单对话框 -->
    <ItemForm
      v-model:visible="itemFormVisible"
      :form-data="currentItem"
      :is-edit="isEditItem"
      :categories="categories"
      :items="items"
      :current-related-items="currentRelatedItems"
      :temp-category-relations="tempItemCategoryRelations"
      @save="handleSaveItem"
      @cancel="closeItemForm"
      @add-category="addCategoryToItem"
      @remove-category="removeCategoryFromItem"
      @add-item-relation="addItemRelation"
      @remove-item-relation="removeItemRelation"
      @upload-image="handleUploadImage"
      @rich-text-created="handleRichTextCreated"
    />

    <!-- 项目分类关系管理对话框 -->
    <RelationshipManager
      v-model:visible="itemCategoriesDialogVisible"
      title="项目分类关系管理"
      :current-relations="currentItemCategories"
      :available-items="availableCategoriesForItem"
      item-key="id"
      item-label="name"
      @add-relation="addCategoryToItem"
      @remove-relation="removeCategoryFromItem"
    />

    <!-- 内容查看对话框 -->
    <ContentViewer
      v-model:visible="contentViewerVisible"
      :content="viewerContent"
      :title="viewerTitle"
      :type="viewerType"
    />
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Document } from '@element-plus/icons-vue'
import ItemForm from './ItemForm.vue'
import RelationshipManager from './RelationshipManager.vue'
import ContentViewer from './ContentViewer.vue'

// Props
const props = defineProps({
  items: {
    type: Array,
    default: () => []
  },
  categories: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Object,
    default: () => ({ items: false })
  },
  tempItemCategoryRelations: {
    type: Array,
    default: () => []
  },
  currentRelatedItems: {
    type: Array,
    default: () => []
  }
})

// Events
const emit = defineEmits([
  'save-item',
  'delete-item',
  'add-category-to-item',
  'remove-category-from-item',
  'update-current-item-categories',
  'add-item-relation',
  'remove-item-relation',
  'upload-image',
  'refresh-data',
  'rich-text-created'
])

// 响应式数据
const itemFormVisible = ref(false)
const itemCategoriesDialogVisible = ref(false)
const contentViewerVisible = ref(false)
const currentItem = ref({})
const isEditItem = ref(false)
const currentItemId = ref(null)
const viewerContent = ref('')
const viewerTitle = ref('')
const viewerType = ref('text')

// 计算属性
const currentItemCategories = computed(() => {
  if (!currentItemId.value) return []
  return props.categories.filter(category => 
    category.items && category.items.some(item => item.id === currentItemId.value)
  )
})

const availableCategoriesForItem = computed(() => {
  if (!currentItemId.value) return props.categories
  return props.categories.filter(category => 
    !category.items || !category.items.some(item => item.id === currentItemId.value)
  )
})

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    'markdown': 'primary',
    'page': 'success',
    'external': 'warning',
    'component': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type) => {
  const typeMap = {
    'markdown': 'Markdown',
    'page': '页面',
    'external': '外部链接',
    'component': '组件'
  }
  return typeMap[type] || type
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 打开项目表单
const openItemForm = () => {
  currentItem.value = {
    title: '',
    description: '',
    type: 'markdown',
    content: '',
    url: '',
    page_id: null,

    component_name: '',
    icon: '',
    params: '{}',
    status: 'active'
  }
  isEditItem.value = false
  itemFormVisible.value = true
}

// 编辑项目
const editItem = (item) => {
  currentItem.value = { ...item }
  isEditItem.value = true
  itemFormVisible.value = true
  emit('update-current-item-categories', item.id)
}

// 关闭项目表单
const closeItemForm = () => {
  itemFormVisible.value = false
  currentItem.value = {}
  isEditItem.value = false
}

// 保存项目
const handleSaveItem = (itemData) => {
  emit('save-item', itemData, isEditItem.value)
  closeItemForm()
}

/**
 * 处理富文本项目创建成功后的跳转
 * @param {Object} itemData - 创建的项目数据
 */
const handleRichTextCreated = (itemData) => {
  emit('rich-text-created', itemData)
}

// 删除项目
const deleteItem = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除项目 "${item.title}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    emit('delete-item', item.id)
  } catch {
    // 用户取消删除
  }
}

// 管理项目分类
const manageItemCategories = (item) => {
  currentItemId.value = item.id
  emit('update-current-item-categories', item.id)
  itemCategoriesDialogVisible.value = true
}

// 添加分类到项目
const addCategoryToItem = (categoryId) => {
  emit('add-category-to-item', currentItemId.value || currentItem.value.id, categoryId)
}

// 从项目移除分类
const removeCategoryFromItem = (categoryId) => {
  emit('remove-category-from-item', currentItemId.value || currentItem.value.id, categoryId)
}

// 添加项目关联
const addItemRelation = (pageItemId, itemId) => {
  emit('add-item-relation', pageItemId, itemId)
}

// 移除项目关联
const removeItemRelation = (pageItemId, itemId) => {
  emit('remove-item-relation', pageItemId, itemId)
}

// 查看内容
const viewContent = (item) => {
  viewerTitle.value = item.title
  
  switch (item.type) {
    case 'markdown':
      viewerContent.value = item.content || '暂无内容'
      viewerType.value = 'markdown'
      break
    case 'external':
      viewerContent.value = item.url || '暂无链接'
      viewerType.value = 'url'
      break
    case 'page':
      let pageInfo = '页面类型项目\n'
      if (item.params) {
        // 页面类型项目无需页面参数
      }
      pageInfo += `关联分类: ${item.categories ? item.categories.map(cat => cat.name).join(', ') : '未设置'}`
      viewerContent.value = pageInfo
      viewerType.value = 'text'
      break
    case 'component':
      viewerContent.value = `组件名称: ${item.component_name || '未设置'}\n参数: ${item.params || '{}'}`
      viewerType.value = 'text'
      break
    default:
      viewerContent.value = '暂无内容'
      viewerType.value = 'text'
  }
  
  contentViewerVisible.value = true
}

// 处理图片上传
const handleUploadImage = (file) => {
  emit('upload-image', file)
}
</script>

<style scoped>
.item-management {
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 6px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  height: 100vh;
  width: calc(100vw - 250px);
  margin: 0;
  position: fixed;
  top: 0;
  left: 250px;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-sizing: border-box;
  overflow: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px 0;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 0;
  backdrop-filter: blur(10px);
  border: none;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  flex-shrink: 0;
  width: 100%;
  margin-left: -12px;
  margin-right: -12px;
  padding-left: 28px;
  padding-right: 28px;
}

.header h2 {
  margin: 0;
  color: white;
  font-size: 28px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 内容区域 */
.content {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 16px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

/* 表格容器 */
.el-table {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 全局按钮样式美化 */
:deep(.el-button) {
  padding: 14px 24px !important;
  font-size: 16px !important;
  font-weight: 600 !important;
  border-radius: 12px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  transition: all 0.3s ease !important;
  border: none !important;
  min-height: 48px !important;
  min-width: 120px !important;
}

:deep(.el-button--default) {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%) !important;
  color: #333 !important;
}

:deep(.el-button--default:hover) {
  background: linear-gradient(135deg, #e3e7f0 0%, #b1c1d8 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2) !important;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important;
  color: white !important;
}

:deep(.el-button--success:hover) {
  background: linear-gradient(135deg, #0e8078 0%, #2dd865 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(17, 153, 142, 0.4) !important;
}

:deep(.el-button--warning) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
  color: white !important;
}

:deep(.el-button--warning:hover) {
  background: linear-gradient(135deg, #ee82f9 0%, #f3455a 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(240, 147, 251, 0.4) !important;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%) !important;
  color: white !important;
}

:deep(.el-button--danger:hover) {
  background: linear-gradient(135deg, #ff5252 0%, #e53e3e 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4) !important;
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: nowrap;
}

/* 表格操作按钮样式 - 确保大小一致 */
:deep(.el-table .el-button) {
  padding: 8px 16px !important;
  font-size: 12px !important;
  min-height: 32px !important;
  min-width: 70px !important;
  flex-shrink: 0;
  white-space: nowrap;
  text-align: center;
}

/* 操作列不换行 */
:deep(.el-table__body .el-table__row .el-table__cell:last-child) {
  white-space: nowrap !important;
}

:deep(.el-table__body .el-table__row .el-table__cell:last-child .cell) {
  white-space: nowrap !important;
  overflow: visible !important;
}

/* 图标样式 */
:deep(.el-icon) {
  margin-right: 8px !important;
  font-size: 18px !important;
}

/* 项目图标显示样式 */
.icon-display {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
}

.item-icon {
  width: 32px;
  height: 32px;
  object-fit: cover;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.default-icon {
  font-size: 24px !important;
  color: #909399;
  margin: 0 !important;
}

/* 表格头部样式 */
:deep(.el-table__header) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

:deep(.el-table th) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  font-weight: 600;
  color: #303133;
}

/* 表格行样式 */
:deep(.el-table tbody tr:hover) {
  background: rgba(64, 158, 255, 0.05);
}

/* 标签样式 */
:deep(.el-tag) {
  padding: 6px 12px !important;
  font-size: 13px !important;
  font-weight: 600 !important;
  border-radius: 8px !important;
  border: none !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important;
  color: white !important;
}

:deep(.el-tag--warning) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
  color: white !important;
}

:deep(.el-tag--danger) {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%) !important;
  color: white !important;
}

:deep(.el-tag--info) {
  background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%) !important;
  color: white !important;
}

/* 滚动条样式 */
:deep(::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(::-webkit-scrollbar-track) {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}
</style>